/*
 * acooly.cn Inc.
 * Copyright (c) 2016 All Rights Reserved.
 * create by zhangpu 
 * date:2016年4月4日
 *
 */
package com.acooly.module.openapi.client.provider.fuiou.marshall;

import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.provider.fuiou.OpenAPIClientFuiouProperties;
import com.acooly.module.openapi.client.provider.fuiou.domain.FuiouApiMessage;
import com.acooly.module.safety.signature.SignerFactory;
import com.acooly.module.safety.support.KeyPair;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @author zhangpu
 */
public class FuiouMarshallSupport {

    protected static final char SPLIT_CHAR = '|';

    @Autowired
    protected OpenAPIClientFuiouProperties openAPIClientFuiouProperties;

    @Autowired
    protected SignerFactory signerFactory;

    private KeyPair keyPair;

    public void setSignerFactory(SignerFactory signerFactory) {
        this.signerFactory = signerFactory;
    }

    public SignerFactory getSignerFactory() {
        return signerFactory;
    }

    protected String getWaitForSign(Map<String, String> message) {
        Map<String, String> treeMap = Maps.newTreeMap();
        for (Map.Entry<String, String> entry : message.entrySet()) {
            if (Strings.equals(openAPIClientFuiouProperties.getSignatrueParamKey(), entry.getKey()) || Strings.equals("resp_desc", entry.getKey())) {
                continue;
            }
            treeMap.put(entry.getKey(), entry.getValue());
        }
        StringBuilder sb = new StringBuilder();
        for (String v : treeMap.values()) {
            sb.append(Strings.trimToEmpty(v)).append(SPLIT_CHAR);
        }
        String waitForSign = sb.substring(0, sb.length() - 1);
        return waitForSign;
    }

    protected void beforeMarshall(FuiouApiMessage message) {
        message.setPartner(openAPIClientFuiouProperties.getPartnerId());
    }


    protected KeyPair getKeyPair() {
        if (keyPair == null) {
            synchronized (this) {
                if (keyPair == null) {
                    keyPair = new KeyPair(openAPIClientFuiouProperties.getPublicKeyPath(),
                            openAPIClientFuiouProperties.getPrivateKeyPath());
                    keyPair.loadKeys();
                }
            }
        }
        return keyPair;
    }


}
